package com.xplay.xpocker.interceptor;

import com.xplay.xpocker.config.ResultFul;
import com.xplay.xpocker.config.ApiInfoProp;
import com.xplay.xpocker.exception.StatusCodeEnum;
import com.xplay.xpocker.util.JacksonStringUtil;
import com.xplay.xpocker.util.ServletUtil;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ClientVersionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            // 注意  这里ajax请求会带上opTIOS请求  此请求为认证

            // 如果是OPTIONS则结束请求
           /* if (HttpMethod.OPTIONS.toString().equals(request.getMethod())) {
                response.setStatus(HttpStatus.NO_CONTENT.value());
                return true;
            }*/
            String version = request.getHeader("client-version");
            if (version != null && !version.equals(ApiInfoProp.getInstance().getVersion())) {
                ResultFul<String> resultFul = ResultFul.init(StatusCodeEnum.UPDATE_VERSION.getCode(), ApiInfoProp.getInstance().getUpdateInfo());
                ServletUtil.whiterObject(response, JacksonStringUtil.objectToString(resultFul));
                return false;
            }
        } catch (Exception e) {
            ResultFul<String> resultFul = ResultFul.init(StatusCodeEnum.ERROR.getCode(), e.getMessage());
            ServletUtil.whiterObject(response, JacksonStringUtil.objectToString(resultFul));
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
